package znck.spring.serviceImp.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContextHolder implements ApplicationContextAware {

	@Autowired
	SyLogImp syLogImp;
	
	private static ApplicationContext applicationContext;
	
	@Override
	public void setApplicationContext(ApplicationContext arg0) throws BeansException {
		// TODO Auto-generated method stub
		SpringContextHolder.applicationContext = arg0;
		syLogImp.debug(SpringContextHolder.class, "applicationContextName： " + applicationContext.getApplicationName()+"  "+"applicationContextId： " + applicationContext.getId() );
	}
	
	 /** 
      * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型. 若是动态代理的bean该方式需要接口类型转换，动态代理类也是实现了响应的接口
      */
	public static Object getBean(String name) { 
		return getApplicationContext().getBean(name);
		} 
	
	/** 
     * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型. 该方式需要获得的bean未被AOP动态代理，否则会找不到相应的bean
     */ 
     public static <T> T getBean(Class<T> requiredType) {
    	 return getApplicationContext().getBean(requiredType); 
    	 } 
     
     
     public static ApplicationContext getApplicationContext() { 
    	 return applicationContext; 
    	 }

}
